package cn.zzp.pet.service.impl;

import cn.zzp.basic.exception.BusinessException;
import cn.zzp.basic.query.BaseQuery;
import cn.zzp.basic.service.impl.BaseServiceImpl;
import cn.zzp.basic.util.*;
import cn.zzp.order.domain.OrderPetAcquisition;
import cn.zzp.order.mapper.OrderPetAcquisitionMapper;
import cn.zzp.org.domain.Employee;
import cn.zzp.org.domain.Shop;
import cn.zzp.org.mapper.EmployeeMapper;
import cn.zzp.org.mapper.ShopLogMapper;
import cn.zzp.org.mapper.ShopMapper;
import cn.zzp.pet.domain.Pet;
import cn.zzp.pet.domain.PetDetail;
import cn.zzp.pet.domain.SearchMasterMsg;
import cn.zzp.pet.domain.SearchMasterMsgAuditLog;
import cn.zzp.pet.dto.AcceptDto;
import cn.zzp.pet.enums.SearchMasterMsgEnum;
import cn.zzp.pet.mapper.PetDetailMapper;
import cn.zzp.pet.mapper.PetMapper;
import cn.zzp.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.zzp.pet.mapper.SearchMasterMsgMapper;
import cn.zzp.pet.query.SearchMasterMsgQuery;
import cn.zzp.pet.service.PetService;
import cn.zzp.pet.service.SearchMasterMsgService;
import cn.zzp.user.domain.LoginInfo;
import cn.zzp.user.domain.User;
import cn.zzp.user.mapper.UserMapper;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;


/**
 * @ClassName
 * @Description
 * @Author 祝志鹏
 * @Date 2022/7/14 14:16
 */
@Service
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Value("${rocketmq.producer.group}")
    private String group;

    @Value("${rocketmq.name-server}")
    private String nameServerAddr;

    @Value("${rocketmq.producer.topic}")
    private String topic;

    @Value("${rocketmq.producer.tag}")
    private String tag;
    /**
     * 发布消息
     *
     * @param searchMasterMsg
     * @param id
     */
    @Transactional
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, Long id) {
        // 获取用户
        User user = userMapper.queryByLoginInfoId(id);
        searchMasterMsg.setUser_id(user.getId());

        // 存储信息
        searchMasterMsgMapper.add(searchMasterMsg);

        // 百度审核【审核文本内容，标题+名字+地址】
        Boolean aBoolean = BaiduAuditUtils.TextCensor(searchMasterMsg.getTitle()
                + searchMasterMsg.getName()
                + searchMasterMsg.getAddress()
        );

        // 审核通过
        if (aBoolean) {
            // 修改寻主状态，分配就近门店，并且发送短信通知，添加审核日志
            searchMasterMsg.setState(SearchMasterMsgEnum.TO_BE_PROCESSED.getState());//1，待处理
            searchMasterMsg.setNote(SearchMasterMsgEnum.TO_BE_PROCESSED.getDes());

            // 分发店铺处理
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop shop = DistanceUtils.getNearestShop(point, shopMapper.queryAll());
            if (shop != null) {
                searchMasterMsg.setShop_id(shop.getId());

                // 发送短信
//                Employee employee = employeeMapper.queryById(shop.getAdmin_id());
//                SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请尽快处理："+searchMasterMsg.getTitle());
                // 没钱模拟发送就行
                System.out.println("你有新的订单，请尽快处理：" + searchMasterMsg.getTitle());
            }
            // 更新数据库数据
            searchMasterMsgMapper.update(searchMasterMsg);

            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsg_id(searchMasterMsg.getId());
            log.setState(searchMasterMsg.getState());
            log.setNote(searchMasterMsg.getNote());

            searchMasterMsgAuditLogMapper.add(log);

        } else { // 驳回审核
            //修改状态和日志
            searchMasterMsg.setState(SearchMasterMsgEnum.DISALLOWING.getState()); //-1, 驳回申请
            searchMasterMsg.setNote(SearchMasterMsgEnum.DISALLOWING.getDes());
            //保存修改
            searchMasterMsgMapper.update(searchMasterMsg);

            // 更新日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(searchMasterMsg.getState());
            log.setNote(searchMasterMsg.getNote());
            log.setMsg_id(searchMasterMsg.getId());

            searchMasterMsgAuditLogMapper.add(log);

            throw new BusinessException("参数违规，请重新输入");

        }
    }

    /**
     * 分页查询
     *
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> pageQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取当前用户
        LoginInfo loginInfo = LoginContext.getLoginInfo(request);
        // 判断当前用户是平台用户还是后台用户
        Integer type = loginInfo.getType();
        if (type == 1) { // 普通用户
            User user = userMapper.queryByLoginInfoId(loginInfo.getId());
            query.setUser_id(user.getId());
        }else { // type == 0 管理人员
            // 查询对应员工信息
            Employee employee = employeeMapper.queryByLoginInfoId(loginInfo.getId());
            // 判断是店铺人员还是平台管理人
            if (employee.getShop_id() != null) { // 店铺人员
                query.setShop_id(employee.getShop_id());
            }

        }

        return super.pageQuery(query);
    }

    /**
     * 拒单
     * @param id
     */
    @Transactional
    @Override
    public void reject(Long id) {
        // 根据id查出数据
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.queryById(id);
        // 修改状态
        searchMasterMsg.setShop_id(null);
        searchMasterMsg.setState(SearchMasterMsgEnum.REJECT.getState());
        searchMasterMsg.setNote(SearchMasterMsgEnum.REJECT.getDes());

        searchMasterMsgMapper.update(searchMasterMsg);

        // 修改 日志
        SearchMasterMsgAuditLog log = searchMasterMsgAuditLogMapper.queryByMsgId(searchMasterMsg.getId());
        log.setState(searchMasterMsg.getState());
        log.setNote(searchMasterMsg.getNote());

        searchMasterMsgAuditLogMapper.update(log);
    }

    /**
     * 接单
     * @param dto
     * @param loginInfo
     */
    @Transactional
    @Override
    public void accept(AcceptDto dto, LoginInfo loginInfo) {
        Long msgId = dto.getMsgId();
        Long emp_id = dto.getHandler();
        String note = dto.getNote();

        // 由于前端只有一个页面处理，接单未完成之前不会修改订单状态，所以需要判断是否点击第一次
        OrderPetAcquisition order = orderPetAcquisitionMapper.queryByMsgId(msgId);

        if (order != null) {
            throw new BusinessException("订单正在处理中......");
        }

        // 第一次点击
        // 生成宠物信息
        SearchMasterMsg smm = searchMasterMsgMapper.queryByMsgId(msgId);
        Pet pet = searchMasterMsg2Pet(smm);
        petMapper.add(pet);

        // 生成订单信息
        order = initOrderPetAcquisition(smm,emp_id, pet);
        orderPetAcquisitionMapper.add(order);

        // 发送延时消息至消费者，消费者收到消息后进行消息进行数据处理
        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setNamesrvAddr(nameServerAddr);
        try {
            producer.start();
            Message message = new Message(topic, tag, order.getOrderSn().getBytes(StandardCharsets.UTF_8));
            message.setDelayTimeLevel(19);
            producer.send(message);
            producer.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成OrderPetAcquisition
     * @param smm
     * @param emp_id
     * @param pet
     * @return
     */
    private OrderPetAcquisition initOrderPetAcquisition(SearchMasterMsg smm, Long emp_id, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        // 生成订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(smm.getUser_id());
        order.setOrderSn(orderSn);
        order.setDigest("【" + smm.getTitle() + "】");

        // 最后确认时间为两天
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        // state默认创建为待处理
        // 价格为收购价格
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(emp_id);
        order.setSearch_master_msg_id(smm.getId());

        return order;
    }

    /**
     * 通过searchMasterMsg生成pet
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());

        return pet;
    }
}
